package cn.com.artemis.security.configuration;

import cn.com.artemis.security.properties.OAuth2ClientProperties;
import cn.com.artemis.security.properties.OAuth2Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;


/**
 * @author enbool
 */
@Configuration
@EnableAuthorizationServer
@AutoConfigureAfter({SecurityAutoConfiguration.class, WebSecurityConfiguration.class})
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter  {

	private final static String REALM = "OAUTH_REALM";

	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	private TokenStore tokenStore;
	
	@Autowired
	private JwtAccessTokenConverter jwtAccessTokenConverter;
	
	@Autowired
	private OAuth2Properties oAuth2Properties;


	@Bean
	public ClientDetailsService clientDetails() {
		return new InMemoryClientDetailsService();
	}

	@Bean
	public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
		StrictHttpFirewall firewall = new StrictHttpFirewall();
		//此处可添加别的规则,目前只设置 允许双 //
		firewall.setAllowUrlEncodedDoubleSlash(true);
		return firewall;
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints
				.tokenStore(tokenStore)
				.authenticationManager(authenticationManager)
				.userDetailsService(userDetailsService)
				.accessTokenConverter(jwtAccessTokenConverter);
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		security.realm(REALM + "/client").tokenKeyAccess("isAuthenticated()");
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		
		InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
		
		if(oAuth2Properties.getClients().length > 0) {
			for(OAuth2ClientProperties client : oAuth2Properties.getClients()) {
				builder.withClient(client.getClientId())
					   .secret(client.getClientSecret())
					   .authorizedGrantTypes("password", "authorization_code", "refresh_token")
					   .scopes("all", "read", "write")
					   .accessTokenValiditySeconds(client.getAccessTokenValiditySeconds())
					   .refreshTokenValiditySeconds(client.getRefreshTokenValiditySeconds());
			}
		}
	}
}
